//
//  SGRegisterOneViewController.m
//  HuaMuJinRong
//
//  Created by mac on 16/4/23.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "SGRegisterViewController.h"
#import "SGRegisterNextViewController.h"
#import "NSString+UserInfo.h"
#import "CaptchaView.h"
#import "TabViewController.h"
@interface SGRegisterViewController ()<HTTPClientDelegate>

@property (weak, nonatomic) IBOutlet SGLoginTextField *phoneNumTextField;
@property (weak, nonatomic) IBOutlet SGLoginTextField *phoneCodeTextField;
@property (weak, nonatomic) IBOutlet SGLoginTextField *tuijianrenTextField;
@property (weak, nonatomic) IBOutlet UIView *pictureCodeBackView;
@property (weak, nonatomic) IBOutlet SGLoginButton *nextButton;

@property (nonatomic,strong) CaptchaView * captchaView;
@property (nonatomic, strong) NetWorkClient *requestClient;

@end

@implementation SGRegisterViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setNavBarBackgroundColor:[UIColor clearColor] andStatusBar:UIStatusBarStyleLightContent];
    [self initNavBarTitle:@"手机快速注册" andLeftItemName:@"返回" andRightItemName:@""];
    
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self.view endEditing:YES];
    
    [self resetNavigationBar];
    if (_requestClient) {
        [_requestClient cancel];
    }
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    _captchaView.frame = CGRectMake(0,0, _pictureCodeBackView.frame.size.width, _pictureCodeBackView.frame.size.height);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
 
    [self initView];
}

- (void)initView {
    
    _phoneNumTextField.font = KFontSize(14);
    _phoneCodeTextField.font = KFontSize(14);
    _tuijianrenTextField.font = KFontSize(14);
    _nextButton.titleLabel.font = KFontSize(16);
    
    _nextButton.isActive = NO;
    _nextButton.clipsToBounds = YES;
    _nextButton.layer.cornerRadius = kCornerRadius;
    
    //显示验证码界面(图形验证码)
    _captchaView = [[CaptchaView alloc] initWithFrame:CGRectMake(0,0, _pictureCodeBackView.frame.size.width, _pictureCodeBackView.frame.size.height)];
    [_pictureCodeBackView addSubview:_captchaView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_phoneNumTextField];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldValueChanged) name:UITextFieldTextDidChangeNotification object:_phoneCodeTextField];
}

- (void)back {
    if (self.flag != 1 ) {
        [self.navigationController popViewControllerAnimated:YES];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
        TabViewController *tabViewController = [[TabViewController alloc] init];
        AppDelegateInstance.window.rootViewController = tabViewController;
    }
}
- (void)textFieldValueChanged
{
    if (![_phoneNumTextField.text isEqualToString:@""] && ![_phoneCodeTextField.text isEqualToString:@""]) {
        _nextButton.isActive = YES;
    }else{
        _nextButton.isActive = NO;
    }
}

- (IBAction)nextButtonClick:(id)sender {    
    
    
    if (![NSString validateMobile:_phoneNumTextField.text]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号！"];
        return;
    }
    if (_phoneCodeTextField.text == nil || _phoneCodeTextField.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入图形验证码！"];
        return;
    }
    BOOL result = [_phoneCodeTextField.text compare:_captchaView.changeString
                                                            options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame;
    if (!result) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的图形验证码！"];
        [_captchaView changeNewCaptcha];
        return;
    }
    [self requestData];
}

- (void)requestData
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    //判断手机号是否注册
    [parameters setObject:@"500" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:_phoneNumTextField.text forKey:@"mobile"];
    [parameters setObject:_tuijianrenTextField.text forKey:@"referrerName"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma mark -------HTTPClientDelegate
-(void) startRequest
{
    
}

-(void) httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj
{
    NSDictionary *dics=(NSDictionary *)obj;
    NSString *errorStr=[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]];
    if ([errorStr isEqualToString:@"-1"]) {
        SGRegisterNextViewController *registerNextVC = [[SGRegisterNextViewController alloc] initWithNibName:@"SGRegisterNextViewController" bundle:nil];
        registerNextVC.phoneNum = _phoneNumTextField.text;
        if (_tuijianrenTextField.text != nil && _tuijianrenTextField.text.length != 0) {
            registerNextVC.referral = _tuijianrenTextField.text;
        }else{
            registerNextVC.referral = @"";
        }
        [self.navigationController pushViewController:registerNextVC animated:YES];
    }else{
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",[dics objectForKey:@"msg"]]];
    }
    
}

-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error
{
    [SVProgressHUD showErrorWithStatus:@"连接服务器失败，请稍后再试"];
}

-(void) networkError
{
    [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
